import { ref } from 'vue'

export function useClipboard() {
  const isSupported = ref(false)
  const isCopying = ref(false)
  const lastError = ref<Error | null>(null)

  // 检查剪贴板API支持
  function checkSupport() {
    isSupported.value = !!(navigator.clipboard && navigator.clipboard.writeText)
    return isSupported.value
  }

  // 复制文本到剪贴板
  async function copyText(text: string): Promise<boolean> {
    if (!text) {
      return false
    }

    isCopying.value = true
    lastError.value = null

    try {
      // 优先使用现代剪贴板API
      if (navigator.clipboard && navigator.clipboard.writeText) {
        await navigator.clipboard.writeText(text)
        return true
      }

      // 降级到传统方法
      return fallbackCopy(text)
    } catch (error) {
      lastError.value = error instanceof Error ? error : new Error('复制失败')
      return false
    } finally {
      isCopying.value = false
    }
  }

  // 传统复制方法（降级方案）
  function fallbackCopy(text: string): boolean {
    try {
      // 创建临时文本区域
      const textArea = document.createElement('textarea')
      textArea.value = text
      textArea.style.position = 'fixed'
      textArea.style.left = '-999999px'
      textArea.style.top = '-999999px'
      document.body.appendChild(textArea)

      // 选择并复制文本
      textArea.focus()
      textArea.select()
      const successful = document.execCommand('copy')

      // 清理
      document.body.removeChild(textArea)

      return successful
    } catch (error) {
      lastError.value = error instanceof Error ? error : new Error('复制失败')
      return false
    }
  }

  // 从剪贴板读取文本
  async function readText(): Promise<string> {
    try {
      if (navigator.clipboard && navigator.clipboard.readText) {
        return await navigator.clipboard.readText()
      }
      throw new Error('剪贴板读取API不支持')
    } catch (error) {
      lastError.value = error instanceof Error ? error : new Error('读取失败')
      return ''
    }
  }

  // 复制并显示反馈
  async function copyWithFeedback(text: string, feedbackDuration: number = 2000): Promise<boolean> {
    const success = await copyText(text)

    if (success) {
      // 可以在这里添加成功反馈逻辑
      console.log('复制成功')
    } else {
      // 可以在这里添加失败反馈逻辑
      console.error('复制失败:', lastError.value?.message)
    }

    return success
  }

  // 初始化
  checkSupport()

  return {
    isSupported,
    isCopying,
    lastError,
    copyText,
    readText,
    copyWithFeedback,
    checkSupport,
  }
}

// 创建剪贴板状态的便捷组合式函数
export function useClipboardState() {
  const { copyText, isSupported, isCopying } = useClipboard()
  const copySuccess = ref(false)
  const copyError = ref<string | null>(null)

  async function copy(text: string): Promise<boolean> {
    copySuccess.value = false
    copyError.value = null

    const success = await copyText(text)

    if (success) {
      copySuccess.value = true
      // 2秒后重置成功状态
      setTimeout(() => {
        copySuccess.value = false
      }, 2000)
    } else {
      copyError.value = '复制失败'
      // 3秒后重置错误状态
      setTimeout(() => {
        copyError.value = null
      }, 3000)
    }

    return success
  }

  return {
    copy,
    isSupported,
    isCopying,
    copySuccess,
    copyError,
  }
}
